package com.sun.audit.config;

import com.sun.audit.handle.AuditLogHandler;
import com.sun.audit.intercept.AuditLogInterceptor;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @author pytho
 */
@Configuration
@AutoConfigureAfter(MybatisAutoConfiguration.class)
public class AuditLogAutoConfiguration {

    private static final Logger log = LoggerFactory.getLogger(AuditLogAutoConfiguration.class);

    @Bean
    @ConditionalOnMissingBean
    public AuditLogInterceptor auditLogInterceptor(ApplicationContext applicationContext) {
        log.info("========== 初始化 AuditLogInterceptor ==========");
        AuditLogInterceptor auditLogInterceptor = new AuditLogInterceptor();
        auditLogInterceptor.setApplicationContext(applicationContext);
        AuditLogHandler auditLogHandler = new AuditLogHandler();
        auditLogInterceptor.setAuditLogHandler(auditLogHandler);
        return auditLogInterceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer(AuditLogInterceptor auditLogInterceptor) {
        log.info("========== 注册拦截器到 MyBatis 配置 ==========");
        return configuration -> configuration.addInterceptor(auditLogInterceptor);
    }
}